package commEnv

import (
	"encoding/json"
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"os"
	"strings"
)

type confLoader struct {
}

func (e *confLoader) LoadConf() error {
	routerPath := Service.WorkDir + "/conf/router.json"
	routerPath = FileName.GetOsFilePath(routerPath)

	// 读取文本文件的内容
	jsn, err := os.ReadFile(routerPath)
	if err != nil {
		return errors.New("装载配置文件失败：/conf/router.json")
	}

	data := make(map[string]interface{})
	err = json.Unmarshal(jsn, &data)

	Service.EdgeId = Map.GetString(data, "edgeId", "")
	Service.Mqtt = Map.GetMap(data, "mqtt", make(map[string]interface{}))

	topic := Map.GetMap(data, "topic", make(map[string]interface{}))
	Service.Topic.Request = Map.GetString(topic, "request", "")
	Service.Topic.Respond = Map.GetString(topic, "respond", "")
	Service.Topic.Request = strings.ReplaceAll(Service.Topic.Request, "{edgeId}", Service.EdgeId)
	Service.Topic.Respond = strings.ReplaceAll(Service.Topic.Respond, "{edgeId}", Service.EdgeId)
	return nil
}
